using Gtk;

namespace Atlantis
{
    public class DocumentService : GLib.Object, IDocumentService, IInjectRegistry
    {
        public Registry Registry { get; set; }
        
        public Document SelectedDocument { get; set; }
        
        construct
        {
			stderr.printf("DocumentService.ctor");
		}
		
        /**
         Opens a document and initializes the SelectedDocument with it.
         */
        public void CreateNewDocument()
        {
            DocumentPresenter presenter = new DocumentPresenter(Registry);
            IDocumentView idocumentView = Registry.Get<IDocumentView>();
            presenter.View = idocumentView;
            
            Registry.Workspaces["DOCUMENT_WORKSPACE"].Add(idocumentView); 
        }

        /**
         
         */
        public void OpenDocument()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            string fileName = "";
            if (dlg.run() == ResponseType.ACCEPT)
            {
                fileName = dlg.get_filename();
                var projectReader = new ProjectReader(fileName);
                var project = projectReader.read_project();
                var agg = Registry.Get<IEventAggregator>();
                var message = new OpenProjectEvent() { Project = project } ;
                agg.send_message<OpenProjectEvent>(message);
                /*
                Document document = new Document(fileName);
                this.SelectedDocument = document;
                DocumentPresenter presenter = new DocumentPresenter(Registry);
                IDocumentView idocumentView = Registry.Get<IDocumentView>();
                presenter.View = idocumentView;
                stderr.printf("presenter.View.Load(document);");
                if (idocumentView == null)
                    stderr.printf("idocumentView == null");
                idocumentView.Load(document);
                stderr.printf("before  this.documentWorkspace.Add(idocumentView);");
                Registry.Workspaces["DOCUMENT_WORKSPACE"].Add(idocumentView);
                stderr.printf("after  this.documentWorkspace.Add(idocumentView);");
                Registry.Workspaces["DOCUMENT_WORKSPACE"].Activate(idocumentView);
                */
            }

            dlg.destroy();
        }
    }
}
